<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Agent;

use App\Dao\AgentBankDao;
use App\Dao\AgentDao;
use App\Dao\AgentMoneyDao;
use App\Dao\BusinessDao;
use App\Dao\LocationDao;
use App\Dao\UserDao;
use App\Kernel\Util\AgentJwtInstance;
use App\Service\Service;

use Hyperf\Di\Annotation\Inject;

/**
 * 合伙人服务
 *
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Admin
 */
class PartnerService extends Service
{
    /**
     * @Inject
     * @var AgentDao
     */
    public $agent_dao;

    /**
     * @Inject
     * @var MoneyService
     */
    public $money_service;

    /**
     * @Inject
     * @var UserDao
     */
    public $user_dao;

    /**
     * @Inject
     * @var BusinessDao
     */
    public $business_dao;

    /**
     * 获取分公司直招合伙人列表
     */
    public function getOfficePartner()
    {
        $agent = $this->agent_dao->mapMany([
            'identity' => 4,
            'inviter_id' => agentId(),
        ]);

        foreach ($agent as $key => $value) {
            $data[$key]['id'] = $value['id'];
            $data[$key]['name'] = $value['name'];
        }

        return $data;
    }

    /**
     * 获取分公司直招的市代
     */
    public function getOfficeCity()
    {
        $agent = $this->agent_dao->mapMany([
            'identity' => 2,
            'inviter_id' => agentId(),
        ]);

        foreach ($agent as $key => $value) {
            $data[$key]['id'] = $value['id'];
            $data[$key]['name'] = $value['name'];
        }

        return $data;
    }

    /**
     * 获取分公司直招的区代
     */
    public function getOfficeArea()
    {
        $agent = $this->agent_dao->mapMany([
            'identity' => 1,
            'inviter_id' => agentId(),
        ]);

        foreach ($agent as $key => $value) {
            $data[$key]['id'] = $value['id'];
            $data[$key]['name'] = $value['name'];
        }

        return $data;
    }

    /**
     * 调整合伙人状态
     * @param int $partner_id
     * @return mixed
     */
    public function setPartnerStatus(int $partner_id)
    {
        $first = $this->agent_dao->first($partner_id);

        switch ($first['status']) {
            case "1"://开启状态
                return $this->agent_dao->updateMap($partner_id,[
                    'status' => 2
                ]);
                break;
            case "2"://禁用状态
                return $this->agent_dao->updateMap($partner_id,[
                    'status' => 1
                ]);
                break;
            default:
                $this->error("USER.STATUS_EXCEPTION");
        }
    }

    /**
     * 删除合伙人
     * @param int $partner_id
     * @return mixed
     */
    public function deletePartner(int $partner_id)
    {
        $first = $this->agent_dao->first($partner_id);

        if($first['identity'] != 4) {
            $this->error("USER.STATUS_EXCEPTION");
        }

        return $this->agent_dao->delete($partner_id);
    }

    /**
     * 合伙人列表
     */
    public function list()
    {
        $agent = AgentJwtInstance::instance()->build()->getAgent();

        $partner = $this->agent_dao->mapMany([
            'inviter_id' => $agent['id'],
            'identity' => 4,
        ],false);

        $data = [];
        if( $partner ) {
            foreach ($partner as $key => $value) {
                $data['list'][$key]['id'] = $value['id'];
                $data['list'][$key]['name'] = $value['name'];
                $data['list'][$key]['status'] = $value['status'];
                $data['list'][$key]['refuse_reason'] = $value['refuse_reason'] ?? '';
                if( $value['status'] == 3 ) {
                    $data['list'][$key]['check_time'] = date('Y.m.d',$value['check_time']);
                } else {
                    $data['list'][$key]['check_time'] = '';
                }

                $partnerNum = $this->money_service->agent_money_dao->sumMoneyBalance([
                    'agent_id' => agentId(),
                    'partner_id' => $value['id'],
                    'type' => 1,
                ]);

                $data['list'][$key]['total_money'] = filterMoney($partnerNum,4) ?? 0;
            }
        }

        $count = $this->agent_dao->count([
            'inviter_id' => $agent['id'],
            'identity' => 4,
        ]);

        $data['count'] = $count;
        return $data;
    }

    /**
     * 合伙人详情
     * @param int $agent_id
     * @return mixed
     */
    public function details(int $agent_id)
    {
        $partner = $this->agent_dao->map([
            'id' => $agent_id
        ]);

        $data['id'] = $partner['id'];
        $data['phone'] = $partner['phone'] ?? '';
        $data['logo'] = $partner['logo'] ?? '';
        $data['name'] = $partner['name'] ?? '';
        $data['contact_name'] = $partner['contact_name'] ?? '';
        $data['link_phone'] = $partner['link_phone'] ?? '';
        $data['address'] = $partner['address'] ?? '';
        $data['settle_name'] = $partner['settle_name'] ?? '';
        $data['settle_idcard_no'] = $partner['settle_idcard_no'] ?? '';
        $data['status'] = $partner['status'];
        $data['created_at'] = date('Y.m.d', $partner['created_at']);

        $city_count = $this->agent_dao->count([
            'inviter_id' => $agent_id,
            'identity' => 2,
        ]);
        $area_count = $this->agent_dao->count([
            'inviter_id' => $agent_id,
            'identity' => 1,
        ]);

        $agentData = $this->agent_dao->mapMany([
            'inviter_id' => $agent_id,
            'identity' => 1,
        ],false);

        $ids = [];
        foreach ($agentData as $item) {
            $ids[] = $item['location_id'];
        }

        $map = [
            'district_id' => ['in',$ids],
            'group_id' => 2,
        ];

        $data['channel_count'] = $this->user_dao->count($map);
        $data['area_count'] = $area_count;
        $data['city_count'] = $city_count;

        return $data;
    }

    /**
     * 合伙人市代列表
     * @param int $agent_id
     * @return mixed
     */
    public function partnerCityList(int $agent_id)
    {
        $partner = $this->agent_dao->mapManyPage([
            'inviter_id' => $agent_id,
            'identity' => 2,
        ],false);

        $data = [];
        $data['list'] = [];
        if( $partner ) {
            foreach ($partner as $key => $value) {

                $business_count = $this->business_dao->count([
                    'city_id' => $value['location_id']
                ]);

                $data['list'][$key]['id'] = $value['id'];
                $data['list'][$key]['name'] = $value['name'];
                $data['list'][$key]['status'] = $value['status'];
                $data['list'][$key]['created_at'] = date('Y.m.d', $value['created_at']);
                $data['list'][$key]['phone'] = $value['phone'];
                $data['list'][$key]['link_phone'] = $value['link_phone'];
                $data['list'][$key]['contact_name'] = $value['contact_name'];
                $data['list'][$key]['address'] = $value['address'];
                $data['list'][$key]['area_store_total'] = $business_count;
                $data['list'][$key]['store_total_water'] = 0;
                $data['list'][$key]['total_commission'] = 0;
            }
        }

        $count = $this->agent_dao->count([
            'inviter_id' => $agent_id,
            'identity' => 2,
        ]);

        $data['count'] = $count;
        return $data;
    }

    /**
     * 合伙人区代列表
     * @param int $agent_id
     * @return mixed
     */
    public function partnerAreaList(int $agent_id)
    {
        $partner = $this->agent_dao->mapManyPage([
            'inviter_id' => $agent_id,
            'identity' => 1,
        ],false);

        $data = [];
        $data['list'] = [];
        if( $partner ) {
            foreach ($partner as $key => $value) {

                $business_count = $this->business_dao->count([
                    'district_id' => $value['location_id']
                ]);

                $data['list'][$key]['id'] = $value['id'];
                $data['list'][$key]['name'] = $value['name'];
                $data['list'][$key]['status'] = $value['status'];
                $data['list'][$key]['created_at'] = date('Y.m.d', $value['created_at']);
                $data['list'][$key]['phone'] = $value['phone'];
                $data['list'][$key]['link_phone'] = $value['link_phone'];
                $data['list'][$key]['contact_name'] = $value['contact_name'];
                $data['list'][$key]['address'] = $value['address'];
                $data['list'][$key]['area_store_total'] = $business_count;
                $data['list'][$key]['store_total_water'] = 0;
                $data['list'][$key]['total_commission'] = 0;
            }
        }

        $count = $this->agent_dao->count([
            'inviter_id' => $agent_id,
            'identity' => 1,
        ]);

        $data['count'] = $count;
        return $data;
    }

    /**
     * 合伙人渠道商列表
     * @param int $agent_id
     * @return mixed
     */
    public function partnerChannelList(int $agent_id)
    {
        $agentData = $this->agent_dao->mapMany([
            'inviter_id' => $agent_id,
            'identity' => 1,
        ],false);

        $ids = [];
        foreach ($agentData as $item) {
            $ids[] = $item['location_id'];
        }

        $map = [
            'district_id' => ['in',$ids],
            'group_id' => 2,
        ];

        $result = $this->user_dao->areaAgent($map);

        $data = [];
        if( $result ) {
            foreach ($result as $key => $value) {
                $data['list'][$key]['id'] = $value['id'];
                $data['list'][$key]['phone'] = $value['phone'];
                $data['list'][$key]['name'] = $value['name'];
                $data['list'][$key]['address'] = $value['province'].$value['city'].$value['district'];
                $data['list'][$key]['belonging'] = $value['district'];
                $data['list'][$key]['status'] = $value['status'];
                $data['list'][$key]['created_at'] = date('Y.m.d',$value['created_at']);

            }
        }
        $data['agent_channel_count'] = $this->user_dao->count($map);

        return $data;
    }

    /**
     * 新增合伙人
     * @param array $params
     * @return mixed
     */
    public function add(array $params)
    {
        $agent = AgentJwtInstance::instance()->build()->getAgent();

        if(  $params['area_agent_money'] > $agent['area_agent_money']) {
            $this->error('AGENT.PART_SERVANT');
        }

        if( $params['city_agent_money'] > $agent['city_agent_money'] ) {
            $this->error('AGENT.PART_SERVANT');
        }

        if( $params['channel_agent_money'] > $agent['channel_agent_money']) {
            $this->error('AGENT.PART_SERVANT');
        }

        $result = $this->agent_dao->create([
            'name' => $params['name'],
            'status' => 0,
            'identity' => 4,
            'phone' => $params['phone'],
            'login_pwd' => password_hash($params['phone'],PASSWORD_DEFAULT),
            'sex' => $params['sex'],
            'link_phone' => $params['link_phone'],
            'contact_name' => $params['contact_name'],
            'address' => $params['address'],
            'corporate_name' => $params['corporate_name'],
            'settle_name' => $params['settle_name'],
            'settle_idcard_no' => $params['settle_idcard_no'],
            'settle_idcard_front' => $params['settle_idcard_front'],
            'settle_idcard_back' => $params['settle_idcard_back'],
            'settle_bank_username' => $params['settle_bank_username'],
            'settle_bank' => $params['settle_bank'],
            'settle_bank_account' => $params['settle_bank_account'],
            'settle_bank_front' => $params['settle_bank_front'],
            'business_license' => $params['business_license'],
            'inviter_id' => $agent['id'],
            'area_agent_money' => $params['area_agent_money'] ?? sConfig('partner_area_money'),
            'city_agent_money' => $params['city_agent_money'] ?? sConfig('partner_city_money'),
            'channel_agent_money' => $params['channel_agent_money'] ?? sConfig('partner_channel_money'),
            'remark' => $params['remark'],
            'updated_at' => time(),
            'created_at' => time(),
        ]);

        return $result;
    }
}